#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <getopt.h>
#include <stdlib.h>
#include <pthread.h>
#include <ctype.h>

#include "cJSON.h"
#include "connect.h"
#include "thread.h"


#define BACKLOG 10

void print_usage(char *progname)
{
	printf("%s usage:\n",progname);
	printf("-p(--port):sepcify server listen port.\n");
	printf("-h(--help):print this help information.\n");

	return ;
}

int main(int argc,char ** argv)
{
	int			socket_fd=-1;
	int			client_fd=-1;
	int			rv=-1;
	int 			ch;
	int			port;
	pthread_t		tid;
	char			buf[1024];
	struct sockaddr_in 	serv_addr;
	struct sockaddr_in 	cli_addr;
	socklen_t		cli_len;
	struct option opts[]={
		{"port",required_argument,NULL,'p'},
		{"help",no_argument,NULL,'h'},
		{NULL,0,NULL,0}
	};

	while((ch=getopt_long(argc,argv,"p:h",opts,NULL))!=-1)
	{
		switch(ch)
		{
			case 'p':
				port=atoi(optarg);
				break;

			case 'h':
				print_usage(argv[0]);
				return 0;
		}

	}
	
	if(!port)
	{
		print_usage(argv[0]);
		return 0;
	}


	socket_connect(&socket_fd,&port);



	while(1)
	{
		printf("Start to connect!\n");
		client_fd=accept(socket_fd,(struct sockaddr *)&cli_addr,&cli_len);

		if(client_fd<0)
		{
			printf("'Accept' failure:%s\n",strerror(errno));
			close(socket_fd);
			return -2;
		}

		printf("Client[%d] connects successfully!\n",client_fd);

		thread_start(&tid,thread_worker,(void *)client_fd);
		
	}

	close(socket_fd);

}






